<?php

/*
 * $Id: select.php 11 2010-11-24 22:10:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-24 22:10:53 +0000 (Wed, 24 Nov 2010) $
 * $Revision: 11 $
 */

namespace cmFly\db\sql_constructors;

abstract class select extends query {
    protected $fields=Array();
    protected $from;
    protected $joins = Array();
    protected $group_by;
    protected $order_by;
    const TYPE_JOIN_LEFT=1;
    const TYPE_DIRECTION_ASC=1;
    const TYPE_DIRECTION_DESC=2;
    const TYPE_DIRECTION_LAST_CLEAN=4;
    public function __construct($connnection) {
	parent::__construct($connnection);
	$this->fields[$this->pseudo_name]=Array('fields'=>Array(),'table_name'=>&$this->from,'user_data'=>&$this->user_data);
    }

    public function from($from) {
	$this->from = $from;
	return $this;
    }

    public function fields(array $fields) {
	$this->fields[$this->pseudo_name]['fields']=$fields;
	return $this;
    }

    public function join(select $join, $type=self::TYPE_JOIN_LEFT) {
	$this->joins[] = Array('join' => $join, 'type' => $type);
	$this->fields[$join->pseudo_name]=&$join->fields[$join->pseudo_name];
	return $this;
    }

    public function order_by($order_field, $order_direction=self::TYPE_DIRECTION_DESC) {
	if($order_direction & self::TYPE_DIRECTION_LAST_CLEAN) {
	    $order_direction&=~self::TYPE_DIRECTION_LAST_CLEAN;
	    $this->order_by=Array();
	}
	if(!$order_direction) {
	    throw new \cmFly\data_model\exception('Direction type not set!');
	}
	$this->order_by[$order_direction][] = $order_field;
	return $this;
    }

    public function group_by($group_field, $group_direction=self::TYPE_DIRECTION_DESC) {
	if($group_direction & self::TYPE_DIRECTION_LAST_CLEAN) {
	    $group_direction&=~self::TYPE_DIRECTION_LAST_CLEAN;
	    $this->group_by=Array();
	}
	if(!$group_direction) {
	    throw new \cmFly\data_model\exception('Direction type not set!');
	}

	$this->group_by[$group_direction][] = $group_field;
	return $this;
    }

    public function query() {
	$query=$this->create_query();
	$st=$this->get_connection()->prepare($query);
	$current_column=1;
	$fields=$this->get_fields();
	foreach($fields as $k=>$v) {
	    foreach($v['fields'] as $field_name=>$field_opts) {
		$type=isset($field_opts['type'])? $field_opts['type'] : \PDO::PARAM_STR;
		$st->bindColumn($current_column++,$fields[$k]['values'][$field_name],$type);
	    }
	}
	$st->execute();

	return new result($st,  \array_values($fields));
    }
    public function get_fields() {
	return $this->fields;
    }
}